#!/usr/bin/env bash

usage() {
  cat <<EOF
A bash script to generate the helm template from given docker image
Usage: itoh [options] -i <reg>/<project>/<image>:<tag>
Options
  -x {true|false}  Update the index of helm repository
  -i <img>         Specify the image going to build from
  -a <app-version> Specify the executable app version(if app version cannot be detected)
  -b {java|nginx}  Specify what the base image is
  -h               Show this help information
  -v               Show verbose information on execution
EOF
}

fatal() {
  echo "$@"
  exit 1
}

fatal "Script has been disabled, please feel free to using java/node/nginx/restheart generic helm chart to deploy your application."

declare -A options
options=(\
  [image]="" [verbose]="" [app]="" [base]="" [new]=false [repository]="" \
  [name]="" [tag]="latest")

while getopts "i:g:t:x:a:b:d:hv" opt
do
  case $opt in
    h) usage && exit ;;
    v) set -x && options[verbose]="-v" ;;
    a) options[app]=$OPTARG ;;
    b) options[base]=$OPTARG ;;
    i) options[image]=$OPTARG ;;
    x) options[new]=$OPTARG ;;
    *) ;;
  esac
done

if [ "${options[new]^^}" != "TRUE" ]
then
  echo "Skip building & updating the Helm index cause missing [-x true] option."
  exit 0
fi

# shellcheck source=$HOME/.itohrc
test -e "$HOME/.itohrc" && . "$HOME/.itohrc"

test -n "${options[image]}" || fatal "Image must not be empty"
test "${options[image]//:/}" != "${options[image]}" && options[tag]="${options[image]##*:}"
options[name]=$(echo "${options[image]}" | sed -E 's#.*/([^:]+)(:.*)?$#\1#g')

next() {
  IFS=" " read -r -a parts <<< "${1//./ }"
  ((parts[2]=parts[2]+1))
  echo "${parts[@]}" | tr ' ' '.'
}

gt() {
  IFS=" " read -r -a lhs <<< "${1//./ }"
  IFS=" " read -r -a rhs <<< "${2//./ }"
  [[ 0 -ge ${#lhs[@]} ]] && return 0
  [[ 0 -ge ${#rhs[@]} ]] && return 0
  for ((i=0;i<${#rhs[@]};++i))
  do
    [ ${lhs[$i]} -gt ${rhs[$i]} ] && return 0
  done
  return 1
}

# here we go
# helm[action]=
#    0 -> create new template
#    1 -> append an entry
#    2 -> append a new release
#    3 -> append a new development
#    4 -> replace an exist development
declare -A helm templates
helm=([version]="" [versions]="" [app]="" [name]="${options[name]}" [target]="" [url]="" [base]="" [indexes]="" [index]="" [action]=0 [created]="$(date +%Y-%m-%dT%H:%M:%S.%s%:z|sed -E 's/^(.+).{3}([+-].+$)/\1\2/g')")
templates=(\
[java]="H4sIFAAAAAAA/ykAK2FIUjBjSE02THk5NWIzVjBkUzVpWlM5Nk9WVjZNV2xqYW5keVRRbz1IZWxtAOw8aXMbt5L5PL+il/YrH2sOSV32TpVfLZ+kTfRiSyxJdiqbSqnAmSYJCwNMAAwlRtH+9i0Ac3Mo0rZWTvYJH6Q5Gn2hu9EAehh/ire4nl719mdEan9BYvbdfbd+v9/f29mx//v9fvN/f/B667vBzmB7b2trsL23911/sPV6Z+s76N87Jy0tVZrI7/pfTasp3F+kkYR+RKmo4AHMtzySJMVt3x/4fS9CFUqaaPtoCD8giyE0tgITIeHHdIySo0blcRJjALk9eXqRYAAkSRgNientzeuIv7Xkj820wv/nhKWo/k8CwBr/390eDBr+v73V7z/6/0O0J3CAE5IyDc4ArFfnRuF7T+B8RhVQBQR+Hr5/150IGROtMYIJZWgADjBkRCLMiaRkzFCBFjBGSIhSGAHlWsBCpBI0xgkjGpXveRJtXNgXKdcBDDyPxmSKgQfwBPZ/GB5/f9g9Og/g7Pxw1H0NE8ojIJBIkaAEE2gsmxar7fi8EmdeeAASE6GoFnIRgMSpH+FcJMq/7oYzQrmvMZz1spteEbEAkpSxkWA0XAQwZFdkoSxDJ3OUkkZGshk6gqDJFK5mQiFEmf6oe+1iYxlHfQ8McAAdK7vueN6yiAPv0zwOoNNVKOcooXugEkn51K/I5Ru53+bcliCh4BM69ZlwYG9DRpRKiJ4F7k2vBE2kMKOmfBJqOse3Ec6he4CpxEvih4wi177hgIb4QTI/k+y/Bce3M62ToNcjUUx5YP/+56cZTZRG2ZU4pUrLRbdvFI1MJL6ah37IUvPacsaCN6/3Bj1HqvdqI2yDDbF1PCeesR6R6iTV5gqAcEXdFQByY5pRAMN3Pw1/PvOM0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tB2kaVXM37V1NRZMM31Rd3pOTv9ybWoOYeL2T/axykDvnXqLT72w8F5xgaBn2PGlgr//t7dfnfHo72HvM/D9I6xXosog5Z7m1g/PuNY9P7XpluiWgvL0qeC3HZC8AsWHgNzcqbPJF+NUNdrUIKYJKq5URcFxU7+S+yPDVDn/6eZ3/lTJnODSi/4+U2C06iOWg6L405wQXKv4DuKOTfN3ylMy4k3vcaa+V/p/X7T6NXj+//PEh7AmOiNUr3Ezpu/+FqjhwmKWUR5TNISHhJZqiKX4NSaWJ9b1BzZAxmTExc5STls5cgkRFNF2gjQZV+wiPvCXCcuTfMnyUSp/QaI2ey/99zH045W4LgdqZBCRKU9sc1fM9/e/7pXAuJ3hPI3mT4eHgOEZXK82dUD+xfh77nT/6UA/s375jPBuZP/lUt+KAENCHhZZrY37NS3gtfXSXeC39CLr0Xvo7NZyHpzHvxX94T+EgkFamC47dHyvMTKT5jqD2fRkgGbrgUnz1/oUIR4eAvIN6P7bE9tse2sv13AAAA//8qBBNZAFYAAA==")

declare -A sha1
sha1=([java]="$(docker inspect adoptopenjdk:11-jre-hotspot | grep -Eo '^\s*"sha256[^"]+"' | awk '{print $1}' | tr '\r\n' ' ' | tr -d '"')" [nginx]="$(docker inspect nginx:1.21.3 | grep -Eo '^\s*"sha256[^"]+"' | awk '{print $1}' | tr '\r\n' ' ' | tr -d '"')" [actual]="")

docker pull "${options[image]}" || true

sha1[actual]="$(docker inspect ${options[image]} | grep -Eo '^\s*"sha256[^"]+"' | awk '{print $1}' | tr '\r\n' ' ' | tr -d '"')"
[[ "${sha1[actual]:0:${#sha1[java]}}" == "${sha1[java]}" ]] && [[ 0 -lt "${#sha1[java]}" ]] && helm[base]="java"
[[ "${sha1[actual]:0:${#sha1[nginx]}}" == "${sha1[nginx]}" ]] && [[ 0 -lt "${#sha1[nginx]}" ]] && helm[base]="nginx"

if [ -e "${options[app]}" -a -d "${options[app]}" ]
then
  echo "Using ${options[app]} as helm template home."
  helm[base]="-"
elif [ 0 -ge "${#helm[base]}" ]
then
  case "${options[base]}" in
    java) helm[base]="java" ;;
    nginx) helm[base]="nginx" ;;
    *) ;;
  esac
fi

[[ 0 -lt "${#helm[base]}" ]] || fatal "Unable to detect base image, neither adoptopenjdk:11-jre-hotspot nor nginx:1.21.3 matched"

declare -A vars
vars=([cwd]="target/helm-${options[name]}" [tgz]="" [target]="" [start]="" [over]="")

rm -rf "${vars[cwd]}"
mkdir -p "${vars[cwd]}"
if [ -z "${options[app]}" ]
then
  # extract template
  [[ "java" == "${helm[base]}" ]] && echo "${templates[java]}"|base64 -d|tar -C "${vars[cwd]}" -xvzf -
  [[ "nginx" == "${helm[base]}" ]] && echo "${templates[nginx]}"|base64 -d|tar -C "${vars[cwd]}" -xvzf -
  mv -vf "${vars[cwd]}/mjm2ntgw" "${vars[cwd]}/${helm[name]}"
  find "${vars[cwd]}" -type f -exec sed -i "s#mjm2ntgw#${helm[name]}#g" {} +
else
  cp -rvf "${options[app]}" "${vars[cwd]}"
fi

[[ -e "${vars[cwd]}" ]] || fatal "Current working directory doesn't exist."

if [ "${helm[base]}" == "java" ]
then
  helm[app]=$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout)
else
  helm[app]=$(grep -Eo "^\s*\"version\"\s*:\s*\"([^\"]+)\",?$" package.json|sed -E 's#^[^:]+:\s*"([^"]+).*$#\1#g')
fi
sed -Ei "s#^appVersion\s*:.*#appVersion: ${helm[app]}#g" "${vars[cwd]}/${helm[name]}/Chart.yaml"

helm[indexes]="$(curl -u "${options[credential]}" -skS ${options[repository]%/}/index.yaml)"
(( 0 < "${#helm[indexes]}" )) || fatal "Index not found, please check your paramters."

grep -qE "^  ${helm[name]}\s*:" <<< "${helm[indexes]}" && ((helm[action]=1))
# parse helm version
helm[versions]=$(echo "${helm[indexes]}" | grep -En " ${helm[name]}-[0-9\.-]+.tgz" | sed -E "s#^.*( )${helm[name]}-([0-9\.-]+).tgz.*#\2#g" | sort -t . -n -r)
declare -A version
version=([product]="" [expect]="")
version[product]=$(echo "${helm[versions]}" | grep -E "[0-9]+\.[0-9]+\.[0-9]+$" | head -n 1)
if [ -z "${version[product]}" ]
then
version[expect]="0.1.0"
else
version[expect]=$(next "${version[product]}")
fi
helm[version]="${version[expect]}"
sed -Ei "s#^version\s*:.*#version: ${helm[version]}#g" "${vars[cwd]}/${helm[name]}/Chart.yaml"
sed -Ei "s#^  repository\s*:.*#  repository: ${options[image]%:*}#g" "${vars[cwd]}/${helm[name]}/values.yaml"
sed -Ei "s#^  tag\s*:.*#  tag: ${options[tag]}#g" "${vars[cwd]}/${helm[name]}/values.yaml"

helm[target]="${helm[name]}-${helm[version]}.tgz"
[[ -d "target" ]] || mkdir -p "target"
vars[tgz]="target/${helm[target]}"
IFS=" " read -r -a files <<< "$(find "${vars[cwd]}" -type f | sed -E "s#${vars[cwd]}/##" | tr '\n' ' ')"
tar --version
tar -C "${vars[cwd]}" --no-same-owner --numeric-owner --owner=0 --group=0 -cvzf "${vars[tgz]}" "${files[@]}"

curl -u "${options[credential]}" "${options[repository]%/}/" --upload-file "${vars[tgz]}" -v
